import { useState } from 'react';
import './DataTable.css';

const DataTable = ({ data }) => {
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' });

  if (!data || data.length === 0) {
    return (
      <div className="data-table-container">
        <div className="table-placeholder">
          <div className="placeholder-icon">📋</div>
          <div className="placeholder-text">暂无数据</div>
        </div>
      </div>
    );
  }

  const columns = Object.keys(data[0]);

  const handleSort = (key) => {
    let direction = 'asc';
    if (sortConfig.key === key && sortConfig.direction === 'asc') {
      direction = 'desc';
    }
    setSortConfig({ key, direction });
  };

  const sortedData = [...data].sort((a, b) => {
    if (!sortConfig.key) return 0;
    
    const aVal = a[sortConfig.key];
    const bVal = b[sortConfig.key];
    
    if (aVal < bVal) {
      return sortConfig.direction === 'asc' ? -1 : 1;
    }
    if (aVal > bVal) {
      return sortConfig.direction === 'asc' ? 1 : -1;
    }
    return 0;
  });

  return (
    <div className="data-table-container">
      <div className="table-wrapper">
        <table className="data-table">
          <thead>
            <tr>
              {columns.map(col => (
                <th 
                  key={col} 
                  onClick={() => handleSort(col)}
                  className={`sortable ${sortConfig.key === col ? `sorted-${sortConfig.direction}` : ''}`}
                >
                  {col}
                  {sortConfig.key === col && (
                    <span className="sort-indicator">
                      {sortConfig.direction === 'asc' ? '↑' : '↓'}
                    </span>
                  )}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sortedData.map((row, index) => (
              <tr key={index}>
                {columns.map(col => (
                  <td key={col}>
                    {typeof row[col] === 'number' ? row[col].toLocaleString() : row[col]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      
      <div className="table-footer">
        <span className="row-count">共 {data.length} 条记录</span>
        <button 
          className="export-button"
          onClick={() => exportToCSV(data)}
          title="导出为CSV"
        >
          📥 导出
        </button>
      </div>
    </div>
  );
};

// 导出CSV功能
const exportToCSV = (data) => {
  if (!data || data.length === 0) return;
  
  const columns = Object.keys(data[0]);
  const csvContent = [
    columns.join(','),
    ...data.map(row => 
      columns.map(col => {
        const value = row[col];
        // 处理包含逗号的值
        return typeof value === 'string' && value.includes(',') 
          ? `"${value}"` 
          : value;
      }).join(',')
    )
  ].join('\n');
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `data_${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

export default DataTable;
